package com.louis.iread.skin;

import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;


public class ResourceManager
{
    private static final String TAG = ResourceManager.class.getName();
    private static final String DEFTYPE_DRAWABLE = "drawable";
    private static final String DEFTYPE_COLOR = "color";
    private Resources mResources;
    private String mPluginPackageName;
    private String mSuffix;
    private Context mContext;

    public ResourceManager(Context context, Resources res, String pluginPackageName, String suffix)
    {
        mContext = context;
        mResources = res;
        mPluginPackageName = pluginPackageName;

        if (suffix == null)
        {
            suffix = "";
        }
        mSuffix = suffix;

    }

    public Drawable getDrawableByName(String name)
    {
        try
        {
            name = appendSuffix(name);
//            Log.d(TAG, "name = " + name + " , " + mPluginPackageName);
            return ContextCompat.getDrawable(mContext, mResources.getIdentifier(name, DEFTYPE_DRAWABLE, mPluginPackageName));
        } catch (Resources.NotFoundException e)
        {
//            Log.e(TAG, "drawable ========= " + name + " =============== not found");
//            e.printStackTrace();
            return null;
        }
    }

    public int getColor(String name) throws Resources.NotFoundException
    {
        name = appendSuffix(name);
//        Log.d(TAG, "name = " + name);
        return ContextCompat.getColor(mContext, mResources.getIdentifier(name, DEFTYPE_COLOR, mPluginPackageName));
    }

    public ColorStateList getColorStateList(String name)
    {
        try
        {
            name = appendSuffix(name);
//            Log.d(TAG, "name = " + name);
            return ContextCompat.getColorStateList(mContext, mResources.getIdentifier(name, DEFTYPE_COLOR, mPluginPackageName));

        } catch (Resources.NotFoundException e)
        {
            e.printStackTrace();
            return null;
        }

    }

    private String appendSuffix(String name)
    {
        if (!TextUtils.isEmpty(mSuffix))
            return name += "_" + mSuffix;
        return name;
    }

}
